package helloworld.web.administrate;

import helloworld.entity.administrate.Role;
import helloworld.entity.administrate.User;
import helloworld.modules.hibernate.Page;
import helloworld.modules.hibernate.PropertyFilter;
import helloworld.modules.struts2.CrudActionSupport;
import helloworld.modules.struts2.Struts2Utils;
import helloworld.service.administrate.UserService;

import java.util.List;

import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

@Namespace("/administrate")
@Results( { @Result(name = CrudActionSupport.RELOAD, location = "user.action", type = "redirect") })
public class UserAction extends CrudActionSupport<User>{

	private static final long serialVersionUID = 7605918102325652493L;

	private UserService userService;

	private Long id;
	private User entity;
	private Page<User> page = new Page<User>(5);
	private List<Long> checkedRoleIds; 
	
	@Override
	public String delete() throws Exception {
		return null;
	}

	@Override
	public String input() throws Exception {
		checkedRoleIds = entity.getRoleIds();
		return INPUT;
	}
	
	/**
	 * input页面显示所有角色列表.
	 */
	public List<Role> getAllRoleList() {
		return userService.getAllRole();
	}

	@Override
	public String list() throws Exception {
				
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest());
		//设置默认排序方式
		if (!page.isOrderBySetted()) {
			page.setOrderBy("id");
			page.setOrder(Page.ASC);
		}
		page = userService.searchUser(page, filters);
		return SUCCESS;
	}

	@Override
	protected void prepareModel() throws Exception {
		if (id != null) {
			entity = userService.getUser(id);
		} else {
			entity = new User();
		}
	}

	@Override
	public String save() throws Exception {
		userService.saveUser(entity,checkedRoleIds);
		addActionMessage("保存用户["+entity.getUsername()+"]成功");
		return RELOAD;
	}

	public User getModel() {
		return entity;
	}

	public void setId(Long id) {
		this.id = id;
	}
	
	public Page<User> getPage() {
		return page;
	}

	public List<Long> getCheckedRoleIds() {
		return checkedRoleIds;
	}
	
	public void setCheckedRoleIds(List<Long> checkedRoleIds) {
		this.checkedRoleIds = checkedRoleIds;
	}

	@Autowired
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

}
